package com.ruoyi.common.utils.sign;
import com.ruoyi.common.core.domain.entity.EncryptedDataEntity;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.lang3.RandomStringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author ：jijinwu
 * @ClassName AESUtils
 * @date ：2024/7/18 - 0:41
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description: AES加解密工具类
 **/
public class AESUtils {

    /**
     * 生成AES密钥
     *
     * @param seed 种子
     * @return 返回AES密钥
     * @throws NoSuchAlgorithmException 异常信息
     */
    private static byte[] generateKey(String seed) throws Exception {
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.setSeed(seed.getBytes(StandardCharsets.UTF_8));

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128, secureRandom);
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    }

    /**
     * AES加密
     *
     * @param content 需要加密的内容
     * @param seed    种子
     * @param iv      偏移量，必须16位
     * @return 返回加密后的内容
     * @throws Exception 异常信息
     */
    public static EncryptedDataEntity encrypt(String content, String seed, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(generateKey(seed), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        String encodeData = Base64.encode(cipher.doFinal(byteContent));
        return new EncryptedDataEntity(encodeData,iv,seed);
    }

    /**
     * AES解密
     *
     * @param encryptedData 需要解密的内容
     * @param seed          种子
     * @param iv            偏移量，必须16位
     * @return 返回解密后的内容
     * @throws Exception 异常信息
     */
    public static String decrypt(String encryptedData, String seed, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] byteContent = Base64.decode(encryptedData);
        SecretKeySpec secretKeySpec = new SecretKeySpec(generateKey(seed), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        return new String(cipher.doFinal(byteContent), StandardCharsets.UTF_8);
    }

}

